// 不处理任何上传操作，仅测试中间件(middleware)

const express = require('express');
const multer = require('multer');

const port = 8080;
const app = express();

let staticMiddleware = express.static('public');
app.use(staticMiddleware);

app.get('/', (req, resp) => {
    resp.redirect('/upload.html');
});

//修改默认的dest
let uploader = multer({
    //设置文件存储路径
    storage: multer.diskStorage({
        destination: (req, file, callback) => {
            // 使用回调函数第二个参数确定文件存储路径
            callback(null, 'uploads');
        },
        filename: (req, file, callback) => {
            // 使用回调函数第二个参数确定上传之后的文件名称
            callback(null, file.fieldname + '-' + Date.now() + '-' + file.originalname);
        }
    })
});

// signleMulterMiddleware( req , resp , next )
let signleMulterMiddleware = uploader.single('upfile');
let str = signleMulterMiddleware.toString();
console.log(str.substring(0, str.indexOf(')') + 1)); // function multerMiddleware(req,res,next)

// arrayMulterMiddleware( req , resp , next )
let arrayMulterMiddleware = uploader.array('upfile', 5);
str = arrayMulterMiddleware.toString();
console.log(str.substring(0, str.indexOf(')') + 1)); // function multerMiddleware(req,res,next)


// <input type="file" name="upload" multiple>
// <input type="file" name="image" multiple>
let fieldArray = [
    { name: 'upload', maxCount: 5 },
    { name: 'image', maxCount: 2 }
];

// fieldsMulterMiddleware( req , resp , next )
let fieldsMulterMiddleware = uploader.fields(fieldArray);
str = fieldsMulterMiddleware.toString();
console.log(str.substring(0, str.indexOf(')') + 1)); // function multerMiddleware(req,res,next)


//app.use('/upload/single', signleMulterMiddleware);

/*
app.post('/upload/single', signleMulterMiddleware, (req, resp, next) => {
    let f = req.file;
    console.log(f.originalname, f.mimetype, f.size);
    next();
}, (req, resp, next) => {
    resp.send('<p>上传成功</p>');
});
*/

app.post('/upload/single', (req, resp) => {
    // 直接调用中间件函数并依次为其传入参数
    signleMulterMiddleware(req, resp, (error) => {
        if (error instanceof multer.MulterError) {
            console.log('multer error: ', error.stack);
            resp.send('<p>上传失败</p>');
        } else if (error) {
            console.log('error: ', error.stack);
            resp.send('<p>上传失败</p>');
        } else {
            let f = req.file;
            console.log(f.originalname, f.mimetype, f.size);
            resp.send('<p>上传成功</p>');
        }
    });
});

app.listen(port);